<template>
  <a-modal
    :open="open"
    width="780px"
    :title="rowData?.id ? '修改预案' : '新增预案'"
    centered
    :ok-button-props="{ disabled: !isCompleted }"
    ok-text="保存"
    @ok="onOk"
    @cancel="onCancel"
  >
    <a-form :model="formState" class="form-style-flex" :label-col="{ style: { width: '110px' } }">
      <a-form-item label="预案编号" v-bind="validateInfos.id" class="w-1/2">
        <a-input v-model:value="formState.id" :disabled="!isAdd" placeholder="请输入" />
      </a-form-item>
      <a-form-item label="预案标题" v-bind="validateInfos.prePlanName" class="w-full">
        <a-input v-model:value="formState.prePlanName" placeholder="请输入" />
      </a-form-item>
      <a-form-item label="预案类型" class="w-1/2">
        <a-input v-model:value="formState.prePlanType" placeholder="请输入" />
      </a-form-item>
      <a-form-item label="主题词" class="w-1/2">
        <a-input v-model:value="formState.keyword" placeholder="请输入" />
      </a-form-item>
      <a-form-item label="编制单位" class="w-1/2">
        <a-input v-model:value="formState.preparedBy" placeholder="请输入" />
      </a-form-item>
      <a-form-item label="编制日期" class="w-1/2">
        <a-date-picker v-model:value="formState.preparedTime" format="YYYY-MM-DD" value-format="YYYY-MM-DD" />
      </a-form-item>
      <a-form-item label="预案内容" class="w-full">
        <a-textarea v-model:value="formState.content" :rows="3" placeholder="请输入" />
      </a-form-item>
      <a-form-item label="抄报单位" class="w-1/2">
        <a-input v-model:value="formState.copyOrganization" placeholder="请输入" />
      </a-form-item>
      <a-form-item label="承办单位" class="w-1/2">
        <a-input v-model:value="formState.organization" placeholder="请输入" />
      </a-form-item>
      <a-form-item label="联系人" class="w-1/2">
        <a-input v-model:value="formState.contacts" placeholder="请输入" />
      </a-form-item>
      <a-form-item label="电话" class="w-1/2">
        <a-input v-model:value="formState.phoneNumber" placeholder="请输入" />
      </a-form-item>
      <a-form-item label="备注" class="w-full">
        <a-textarea v-model:value="formState.memo" :rows="1" placeholder="请输入" />
      </a-form-item>
      <a-form-item label="制表人" class="w-1/2">
        <a-input v-model:value="formState.createUser" placeholder="请输入" />
      </a-form-item>
      <a-form-item label="预案文件" class="w-1/2">
        <a-upload :file-list="fileList" accept=".doc,.docx,.pdf" :custom-request="beforeUpload" @remove="handleRemove">
          <a-button>
            <upload-outlined />
            上传文档
          </a-button>
        </a-upload>
      </a-form-item>
    </a-form>
  </a-modal>
</template>
<script setup>
import { ref, watch } from 'vue'
import dayjs from 'dayjs'
import { message } from 'ant-design-vue'
import { UploadOutlined } from '@ant-design/icons-vue'
import axios from 'axios'
import { post } from '@/utils/request'

const emit = defineEmits(['update:open', 'ok'])
const props = defineProps({
  open: {
    type: Boolean,
    default: false
  },
  rowData: {
    type: Object,
    default: () => ({})
  }
})
const isAdd = ref(true)
const planData = ref([])
const formState = ref({
  id: '',
  prePlanName: '',
  prePlanType: '',
  keyword: '',
  preparedBy: '',
  preparedTime: '',
  content: '',
  copyOrganization: '',
  organization: '',
  contacts: '',
  phoneNumber: '',
  memo: '',
  createUser: ''
})
const fileList = ref([])
const rulesState = ref({
  id: [{ required: true, message: '请输入预案编号' }],
  prePlanName: [{ required: true, message: '请输入预案标题' }]
})
const { isCompleted, resetFields, validate, validateInfos } = useForm(formState, rulesState)

watch(
  () => props.open,
  (val) => {
    if (val) {
      getPlanData()
      if (props.rowData?.id) {
        formState.value = props.rowData
        isAdd.value = false
        if (formState.value.fileName && formState.value.fileUrl) {
          fileList.value = [
            {
              uid: fileList.value.length,
              name: formState.value.fileName,
              status: 'done',
              url: formState.value.fileUrl
            }
          ]
        }
      } else {
        isAdd.value = true
        fileList.value = []
        formState.value.preparedTime = dayjs().format('YYYY-MM-DD')
      }
    }
  }
)
const beforeUpload = async (options) => {
  const { file } = options
  const isJpgOrPng = file.type === 'application/msword' || 'application/vnd.openxmlformats-officedocument.wordprocessingml.document' || 'application/pdf'
  if (!isJpgOrPng) {
    message.error('请上传Word或pdf格式文件!')
    fileList.value = fileList.value.filter((item) => {
      return !item.type
    })
    return
  }
  const isLt2M = file.size / 1024 / 1024 < 10
  if (!isLt2M) {
    message.error('上传文件最大10MB!')
    return
  }
  const formData = new FormData()
  formData.append('file', file)
  fileList.value = fileList.value.filter((item) => {
    return item.url
  })
  const { data: res } = await axios.post('/api/v1/common/util/doUploadFile', formData, { headers: { 'Content-Type': 'multipart/form-data' } })
  if (res.code !== 0) return message.error(res.msg)
  fileList.value = [
    {
      uid: fileList.value.length,
      name: file.name,
      status: 'done',
      url: res.data.picturePath
    }
  ]
  formState.value.fileName = file.name
  formState.value.fileUrl = res.data.picturePath
}
const handleRemove = (file) => {
  const index = fileList.value.indexOf(file)
  const newFileList = fileList.value.slice()
  newFileList.splice(index, 1)
  fileList.value = newFileList
  formState.value.fileName = ''
  formState.value.fileUrl = ''
}
const getPlanData = async () => {
  const { code, data, msg } = await post('/war/warEvacuationPlan/getWarEvacuationPlanList', formState.value)
  if (code === -1) return message.error(msg)
  planData.value = data || []
}
const onCancel = () => {
  emit('update:open', false)
  resetFields()
  formState.value = {
    id: '',
    prePlanName: '',
    prePlanType: '',
    keyword: '',
    preparedBy: '',
    preparedTime: '',
    content: '',
    copyOrganization: '',
    organization: '',
    contacts: '',
    phoneNumber: '',
    memo: '',
    createUser: ''
  }
}
const onOk = async () => {
  await validate()
  const { code, msg } = await post('/war/warPrePlan/doSaveWarPrePlan', {
    ...formState.value,
    isPublish: isAdd.value ? '0' : formState.value.isPublish,
    isReport: isAdd.value ? '0' : formState.value.isReport,
    status: isAdd.value ? '0' : formState.value.status
  })
  if (code === 0) {
    message.success('保存成功')
    onCancel()
    emit('ok')
  } else {
    message.error(msg)
  }
}
</script>
